// pages/doctor/home/home.js
import Message from 'tdesign-miniprogram/message/index';

var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //所有患者
    allPatients: [],
    //收藏的患者
    collectedPatients: [],
    collectedPatientsIdList: [],
    //访问过的患者
    visitedPatients: [],
    //查找的患者
    searchedPatients: [],

    //显示添加/删除收藏患者对话框
    showCollectedAddDialog: false,
    showCollectedDeleteDialog: false,
    showAddPatientDiglog: false,
    //正在添加的患者
    patientNameAdding: null,
    patientIdAdding: null,
    //正在删除的患者
    patientNameDeleting: null,
    patientIdDeleting: null,

    //准备收藏的患者id数组
    idAddList: [],
    //准备删除的患者id数组
    idDeleteList: [],

    //搜索框聚焦后显示的内容
    actionText: "",
    //搜索框内容
    searchValue: "",

    //正在开发对话框
    showDeveloping: false,

    //遮罩层
    overlayVisible: false,

    // 新添加患者的姓名和电话
    patient_name: '',
    patient_name_error: true,
    patient_phone: '',
    patient_phone_error: true,
  },
  // 是否显示正在开发对话框
  changeDeveloping(e) {
    this.setData({
      showDeveloping: e.detail
    })
  },
  // 跳转到添加饮食界面
  goPatient(e) {
    console.log("组件接收数据：", e)
    var id = parseInt(e.currentTarget.dataset.id);
    var index = e.currentTarget.dataset.index;
    var title = e.currentTarget.dataset.title;
    console.log("id", id)
    console.log("index", index)
    console.log("title", title)

    if (title != 'test-patient') {
      console.log(this.data[title][index])
      // this.addVisitedPatients(this.data[title][index])
    }
    this.setData({
      showDeveloping: true
    })
    wx.navigateTo({
      url: '/pages/doctor/patient/patient?id=' + id,
    })
  },
  // 点击收藏按钮
  collectChange(e) {
    console.log(e)
    var id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;
    var title = e.currentTarget.dataset.title;
    if (this.data.collectedPatientsIdList.includes(id)) {
      this.setData({
        patientNameDeleting: this.data[title][index].username,
        patientIdDeleting: this.data[title][index].id,
        showCollectedDeleteDialog: true
      })
    } else {
      this.setData({
        patientNameAdding: this.data[title][index].username,
        patientIdAdding: this.data[title][index].id,
        showCollectedAddDialog: true
      })
    }
  },

  //确认收藏患者
  collectedAddDialogConfirm(e) {
    // var idAddlist=this.data.idAddlist;
    var idAddlist = [];
    idAddlist.push(this.data.patientIdAdding);
    this.addCollectedPatients(idAddlist);
    this.setData({
      showCollectedAddDialog: false,
      idAddlist: idAddlist
    })
    this.getCollectedPatients()

  },

  //确认删除患者
  collectedDeleteDialogConfirm(e) {
    // var idDeletelist=this.data.idDeletelist;
    var idDeletelist = [];
    idDeletelist.push(this.data.patientIdDeleting);
    this.deteleCollectedPatients(idDeletelist);
    this.setData({
      showCollectedDeleteDialog: false,
      idDeletelist: idDeletelist
    })
    this.getCollectedPatients()
  },

  //取消对话框
  collectedAddDialogCancel(e) {
    this.setData({
      showCollectedAddDialog: false
    })
  },
  collectedDeleteDialogCancel(e) {
    this.setData({
      showCollectedDeleteDialog: false
    })
  },

  //搜索框聚焦
  focusHandle(e) {
    this.setData({
      // overlayVisible: true
      actionText: "取消"
    })
    var name = e.detail.value;
    if (name.length > 0) {
      this.searchPatients(name)
    }
  },
  actionHandle(e) {
    this.setData({
      actionText: "",
      searchValue: "",
      searchedPatients: []
    })
  },
  blurHandle(e) {
    // this.setData({
    //     searchedPatients:[]
    // })
  },
  searchHandle(e) {
    var name = e.detail.value;
    if (name.length > 0)
      this.searchPatients(name);
    else {
      this.setData({
        searchedPatients: []
      })
    }
  },
  clearHandle(e) {
    this.setData({
      searchedPatients: []
    })
  },

  //遮罩层点击事件
  handleOverlayClick(e) {
    this.setData({
      overlayVisible: e.detail.visible,
    });
  },


  //添加收藏患者
  addCollectedPatients: function (idList) {
    wx.request({
      url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/doctor?Action=AddPatients`,
      method: 'POST',
      header: {
        "Content-Type": "application/json",
        "x-api-key": wx.getStorageSync('token')
      },
      data: {
        "patients": idList
      },
      success: (res) => {
        console.log(res);
        this.getCollectedPatients();
        Message.success({
          context: this,
          offset: [0, 0],
          duration: 2000,
          content: '添加成功',
        });
      }
    })
  },

  //删除收藏患者
  deteleCollectedPatients: function (idList) {
    wx.request({
      url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/doctor?Action=DeletePatients`,
      method: 'POST',
      header: {
        "Content-Type": "application/json",
        "x-api-key": wx.getStorageSync('token')
      },
      data: {
        "patients": idList
      },
      success: (res) => {
        console.log(res);
        this.getCollectedPatients();
        Message.success({
          context: this,
          offset: [0, 0],
          duration: 2000,
          content: '删除成功',
        });
      }
    })
  },
  //搜索患者
  searchPatients: function (name) {
    wx.request({
      url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/doctor?Action=GetAllPatients`,
      method: 'POST',
      header: {
        "Content-Type": "application/json",
        "x-api-key": wx.getStorageSync('token')
      },
      data: {
        "username": name
      },
      success: (res) => {
        // console.log(res);
        if (res.data.code === 200) {
          var patients = res.data.message.patients;
          var searchedPatients = [];
          if (patients != null && patients.length > 0)
            for (var item of patients) {
              searchedPatients.push(item);
            }
          this.setData({
            searchedPatients: searchedPatients,
          });
        }
      },
      fail: (res) => {
        console.log("搜索患者故障")
        Message.error({
          context: this,
          offset: [0, 0],
          duration: 2500,
          content: '服务器故障，我们将尽快维修',
        });
      }
    })
  },
  //获取收藏的患者
  getCollectedPatients: function () {
    wx.request({
      url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/doctor?Action=GetPatients`,
      method: 'GET',
      header: {
        // "Content-Type": "application/json",
        "x-api-key": wx.getStorageSync('token')
      },
      success: (res) => {
        // console.log(res.data.message);
        if (res.data.code === 200) {
          var patients = res.data.message.patients;

          // 检查 patients 是否为有效数组
          if (Array.isArray(patients)) {
            var thiscollectedPatients = [];
            var thisCollectedPatientsIdList = [];
            for (var item of patients) {
              thiscollectedPatients.push(item);
              thisCollectedPatientsIdList.push(item.id);
            }
            this.setData({
              collectedPatients: thiscollectedPatients,
              collectedPatientsIdList: thisCollectedPatientsIdList
            });
          } 
          // else {
          //   console.error("patients组数无效", patients);
          // }
        }
      }
    })
  },

  //获取所有患者信息
  getAllPatient: function () {
    wx.request({
      url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/doctor?Action=GetAllPatients`,
      method: 'GET',
      header: {
        // "Content-Type": "application/json",
        "x-api-key": wx.getStorageSync('token')
      },
      success: (res) => {
        console.log(res);
        if (res.data.code === 200) {
          var patients = res.data.message.patients;
          var list = [];
          for (var patient of patients) {
            list.push(patient);
          }
          this.setData({
            allPatients: list
          })
        }

      }
    })
  },

  // addVisitedPatients: function (patient) {
  //   var visitedPatients = this.data.visitedPatients
  //   var index = visitedPatients.findIndex(item => item.id === patient.id);
  //   if (index != -1) {
  //     visitedPatients.splice(index, 1)
  //   }
  //   visitedPatients.unshift(patient);
  //   if (visitedPatients.length > 3) {
  //     visitedPatients.pop();
  //   }
  //   this.setData({
  //     visitedPatients: visitedPatients
  //   })
  // },
  addVisitedPatients: function (patient) {
    // 确保 visitedPatients 是一个数组
    var visitedPatients = this.data.visitedPatients;
    if (!Array.isArray(visitedPatients)) {
      console.error('visitedPatients should be an array');
      return; // 退出函数
    }

    var index = visitedPatients.findIndex(item =>
      typeof item === 'object' && item !== null && 'id' in item && item.id === patient.id
    );

    // 如果找到相同 id 的患者，则移除
    if (index !== -1) {
      visitedPatients.splice(index, 1);
    }

    // 将新患者添加到数组的开始位置
    visitedPatients.unshift(patient);

    // 如果患者数量超过3个，则移除最后一个
    if (visitedPatients.length > 3) {
      visitedPatients.pop();
    }

    // 更新数据
    this.setData({
      visitedPatients: visitedPatients
    });
  },


  toggleAddPatientDialog() {
    this.setData({
      showAddPatientDialog: !this.data.showAddPatientDialog
    }, function () {
      // 数据更新后的回调函数
      console.log("toggleAddPatientDialog", this.data.showAddPatientDialog);
    });
  },

  // 检查输入是否合理
  validateInputFormat(mode, input) {
    const trimmedInput = input.trim(); // 去除首尾空格

    // 检查输入是否为空
    if (!trimmedInput) {
      return false;
    }

    switch (mode) {
      case 'patient_name':
        return this.validatePatientName(trimmedInput);

      case 'patient_phone':
        return this.validatePatientPhone(trimmedInput);

      default:
        return false;
    }
  },
  validatePatientName(value) {
    // 校验食物名称是否为中英文字符
    const patientNamePattern = /^[a-zA-Z0-9_\u4e00-\u9fa5]{1,20}$/;
    return patientNamePattern.test(value);
  },
  validatePatientPhone(value) {
    // console.log('验证患者电话')
    const phonePattern = /^1[3-9]\d{9}$/;
    return phonePattern.test(value);
  },


  // 绑定到输入框的事件处理函数
  onInputChange(e) {
    const {
      mode
    } = e.currentTarget.dataset;
    const value = e.detail.value;
    if (this.validateInputFormat(mode, value)) {
      // console.log("输入符合规范")
      this.setData({
        [`${mode}`]: value,
        [`${mode}_error`]: false
      })
    } else {
      // console.log("输入格式错误",mode)
      this.setData({
        [`${mode}_error`]: true
      })
    }
  },
  // 确认添加患者的处理函数
  addPatient() {
    if (!this.data.patient_name_error && !this.data.patient_phone_error) {
      // 如果没有错误，则处理添加患者的逻辑
      console.log('添加患者', this.data.patient_name, this.data.patient_phone);
      wx.request({
        url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/doctor?Action=CreatePatient`,
        method: 'POST',
        header: {
          "Content-Type": "application/json",
          "x-api-key": wx.getStorageSync('token')
        },
        data: {
          "name": this.data.patient_name,
          "phone": this.data.patient_phone
        },
        success: (res) => {
          console.log('添加患者成功', res)
          Message.success({
            context: this,
            offset: [20, 32],
            duration: 1000,
            content: '添加患者成功',
          });
        },
        fail: (res) => {
          console.log('添加患者失败', res)
          Message.error({
            context: this,
            offset: [20, 32],
            duration: 1000,
            content: '添加患者失败',
          });
        }
      })

      this.toggleAddPatientDialog(); // 关闭对话框
    } else if (!this.data.patient_phone) {
      Message.info({
        context: this,
        offset: [20, 32],
        duration: 1000,
        content: '请输入正确的电话号码',
      });
    } else {
      Message.info({
        context: this,
        offset: [20, 32],
        duration: 1000,
        content: '请输入正确的患者姓名',
      });
    }
  },

  goAddPatient() {
    wx.navigateTo({
      url: '/pages/doctor/addpatient/addpatient'
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
    this.getAllPatient();
    this.getCollectedPatients();
    var visitedPatients = wx.getStorageSync('visitedPatients')
    this.setData({
      visitedPatients: visitedPatients
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    wx.setStorageSync('visitedPatients', this.data.visitedPatients);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.setStorageSync('visitedPatients', this.data.visitedPatients);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})